import axios from 'axios'
import store from '@/store'
import Session from '@/core/session'
import rspFunc from '@/core/request/response'
import { Loading } from 'element-ui'

const Http = axios.create({
  baseURL: '/api', // 因为我本地做了反向代理
  timeout: 60000,
  responseType: 'json',
  withCredentials: false, // 是否允许带cookie这些
  headers: {
    'Content-Type': 'application/json;charset=utf-8'
  }
})

Http.interceptors.request.use(
  config => {
    // 在发送请求之前做某件事
    if (config.method === 'post') {
      // console.log('config', config)
      // 序列化 改变 header 头中的 Content-Type
      if (config.data) {
        let data = config.data
        config.data = JSON.stringify(data)
      }
    }
    // 在发送请求之前做某件事
    if (Session.jsessionid()) {
      config.headers.Authorization = Session.jsessionid()
    }
    return config
  },
  error => {
    return Promise.reject(error.data.error.message)
  }
)

// 返回状态判断(添加响应拦截器)
Http.interceptors.response.use(
  response => {
    return rspFunc.response(response)
  },
  error => {
    return rspFunc.error(error)
  }
)

export async function jpost (url, data = {}) {
  if (rspFunc.httpUser === false) {
    return new Promise()
  }
  if (url === '/user' || /\/login\?s=\d+/.test(url)) {
    return new Promise((resolve, reject) => {
      var loadingInstance = Loading.service({
        lock: true,
        text: 'Loading',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      })
      Http
        .post(url, data)
        .then(response => {
          if (url === '/user') {
            store.commit('user_info', {
              response
            })
          }
          resolve(response)
        })
        .catch(err => {
          reject(err)
        }).finally(() => {
          if (loadingInstance) {
            loadingInstance.close()
          }
        })
    })
  }
  if (store.state.user && store.state.user.loginUserId && store.state.user.isLogin === true) {
    return new Promise((resolve, reject) => {
      Http
        .post(url, data)
        .then(response => {
          resolve(response)
        })
        .catch(err => {
          reject(err)
        })
    })
  }

  await new Promise((resolve, reject) => {
    var loadingInstance = Loading.service({
      lock: true,
      text: 'Loading',
      spinner: 'el-icon-loading',
      background: 'rgba(0, 0, 0, 0.7)'
    })
    Http
      .post('/user')
      .then(response => {
        if (!response) {
          return
        }
        store.commit('user_info', {
          response
        })
        resolve(response)
      })
      .catch(err => {
        reject(err)
      }).finally(() => {
        if (loadingInstance) {
          loadingInstance.close()
        }
      })
  })
  return new Promise((resolve, reject) => {
    Http
      .post(url, data)
      .then(response => {
        resolve(response)
      })
      .catch(err => {
        reject(err)
      })
  })
}
